package com.wangzhixuan.controller.admin;

import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.result.Result;
import com.wangzhixuan.commons.result.Tree;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.model.Resource;
import com.wangzhixuan.service.IResourceService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @description：资源管理
 * @author：zhixuan.wang
 * @date：2015/10/1 14:51
 */
@Api(tags = "3. 资源管理")
@RestController
@RequestMapping("/admin/resource")
public class ResourceController extends BaseController {

    @Autowired
    private IResourceService resourceService;

    /**
     * 菜单树
     *
     * @return
     */
    @GetMapping("/slideMenu")
    public Result<List<Tree>> slideMenu() {
        ShiroUser shiroUser = getShiroUser();
        return renderObj(resourceService.selectTree(shiroUser));
    }

    /**
     * 资源管理列表
     *
     * @return
     */
    @GetMapping("/treeGrid")
    public Result<List<Tree>> treeGrid() {
        return renderObj(resourceService.selectAll());
    }

    /**
     * 添加资源
     *
     * @param resource
     * @return
     */
    @PutMapping("/add")
    public Result<String> add(@Valid Resource resource) {
        resource.setCreateTime(new Date());
        // 选择菜单时将openMode设置为null
        Integer type = resource.getResourceType();
        if (null != type && type == 0) {
            resource.setOpenMode(null);
        }
        resourceService.save(resource);
        return renderSuccess("添加成功！");
    }

    /**
     * 查询所有的菜单
     */
    @GetMapping("/allTree")
    public Result<List<Tree>> allMenu() {
        return renderObj(resourceService.selectAllMenu());
    }

    /**
     * 查询所有的资源tree
     */
    @GetMapping("/allTrees")
    public Result<List<Tree>> allTree() {
        return renderObj(resourceService.selectAllTree());
    }

    /**
     * 编辑资源
     *
     * @param resource
     * @return
     */
    @PostMapping("/edit")
    public Result<String> edit(@Valid Resource resource) {
        resourceService.updateById(resource);
        return renderSuccess("编辑成功！");
    }

    /**
     * 删除资源
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result<String> delete(Long id) {
        resourceService.removeById(id);
        return renderSuccess("删除成功！");
    }

}
